import React, { useEffect, useState } from 'react'
import { Button, message, Modal, Space, Table, Checkbox, Drawer, Empty, notification, Spin, Typography } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import {
  qualityBatchCancel,
  qualityExecute,
  qualityexport,
  qualityQuery,
  qualityReply,
  qualityTodo,
} from '@/api/purchase'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns, useInnerColumns } from './columns'
import { QualityOrderVO as ITableData } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import CustomTable from '@/components/CustomTable'
import { applicationTypeEnum, OperationLogType } from '@/constant'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import { UploadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { getSpuOptions } from '@/api/goods'
import { QC_STATUS_OPTIONS } from '@/constant/purchase'
import useSearchUser from '@/hooks/useSearchUser'
import { useFormCon, useFormReply, useFormRun } from './useForm'
import { exportNotification, getRecentSixMonths } from '@/utils/util'
import { onValuesChange } from '@/utils/onValuesChange'
import LogsDrawer from '@/components/LogsDrawer'
import useViewLogs from '@/hooks/useViewLogs'
import PermissionButton from '@/components/PermissionButton'
import useGetClassIds from '@/hooks/useGetClassIds'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useCachePage from '@/hooks/useCachePage'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormReply] = useForm()
  const [FormRun] = useForm()
  const [FormCon] = useForm()
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [replyModalShow, setreplyModalShow] = useState<boolean>(false)
  const [runModalShow, setrunModalShow] = useState<boolean>(false)
  const [conModalShow, setconModalShow] = useState<boolean>(false)
  const [expand, setexpand] = useState<boolean>(false)
  const [exportLoading, setexportLoading] = useState(false)
  const [CurrentInfo, setCurrentInfo] = useState<Record<string, any>>({})
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const [expandedRowKeys, setexpandedRowKeys] = useState<React.Key[]>([])
  const [CountNum, setCountNum] = useState<{ waitingReply: number; waitingExecute: number }>({
    waitingReply: 0,
    waitingExecute: 0,
  })
  const [spinning, setspinning] = useState<boolean>(false)
  const { classIdOptions, settinyClassIds, tinyClassIds, handleClassIdChange } = useGetClassIds()
  const defaultDateRange = getRecentSixMonths()
  const [query] = useSearchParams()
  const qualityOrderCode = query.get('qualityOrderCode') || ''
  const { setCachePage, getCachePage } = useCachePage()
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'qualityOrderCode',
    OperationLogType.QUALITY,
  )
  const user_info = useAppSelector((state) => state.user.user_info)
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(qualityQuery, {
    form: form,
    defaultFieldsParams: {
      createTimeStart: qualityOrderCode ? null : defaultDateRange,
      qualityOrderCode,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
  })
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()
  const {
    UserOptions: QcUserOptions,
    handleSearchUser: handleSearchQcUser,
    setUserOptions: setQcUserOptions,
  } = useSearchUser()
  useEffect(() => {
    handleCacheData()
    getqualityTodo()
  }, [])
  useEffect(() => {
    const data = tableProps?.dataSource?.map((item) => item.qualityOrderId)
    if (expand) {
      setexpandedRowKeys(data)
    } else {
      setexpandedRowKeys([])
    }
  }, [tableProps.dataSource, expand])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null || qualityOrderCode) {
      const paramsData = {
        ...params,
        createTimeStart: qualityOrderCode ? null : dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
        createTimeEnd: qualityOrderCode ? null : dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
        purchaseOrderCodes: cacheData?.purchaseOrderCodes != null ? cacheData.purchaseOrderCodes : null,
        qualityOrderCode,
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      if (cacheData.tinyClassId && cacheData.tinyClassId.length > 0) {
        settinyClassIds(cacheData.queryClassIdList)
      }
      form.setFieldsValue({
        ...cacheData,
        createTimeStart:
          cacheData.createTimeStart && cacheData.createTimeEnd
            ? [dayjs(cacheData.createTimeStart), dayjs(cacheData.createTimeEnd)]
            : null,
        scheduleQualityTimeStart:
          cacheData.scheduleQualityTimeStart && cacheData.scheduleQualityTimeEnd
            ? [dayjs(cacheData.scheduleQualityTimeStart), dayjs(cacheData.scheduleQualityTimeEnd)]
            : null,
        queryClassIdList: cacheData?.tinyClassId,
      })
      setSpuOptions(cacheData?.SpuOptions || [])
      setSupplierOption(cacheData?.SupplierOption || [])
      setQcUserOptions(cacheData?.QcUserOptions || [])
      setUserOptions(cacheData?.UserOptions || [])
      delete cacheData.SupplierOption
      delete cacheData.SpuOptions
      delete cacheData.QcUserOptions
      delete cacheData.UserOptions
      search({
        ...cacheData,
        createTimeStart: cacheData.createTimeStart ? cacheData.createTimeStart : null,
        createTimeEnd: cacheData.createTimeEnd ? cacheData.createTimeEnd : null,
        scheduleQualityTimeStart: cacheData?.scheduleQualityTimeStart ? cacheData?.scheduleQualityTimeStart : null,
        scheduleQualityTimeEnd: cacheData?.scheduleQualityTimeEnd ? cacheData?.scheduleQualityTimeEnd : null,
        trackOrderPerson: isRoot ? (cacheData.trackOrderPerson ? cacheData.trackOrderPerson : null) : null,
      })
    }
  }
  const getqualityTodo = async () => {
    const res = await qualityTodo<{ waitingReply: number; waitingExecute: number }>()
    if (res.code == 200) {
      setCountNum(res?.data)
    } else {
      setCountNum({
        waitingReply: 0,
        waitingExecute: 0,
      })
    }
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(info)
  }
  const expandedRowRender = (rows: ITableData) => {
    return (
      <Table
        rowKey={(rows) => rows.qualityOrderDetailId}
        columns={useInnerColumns()}
        dataSource={rows.detailVOS || []}
        pagination={false}
        scroll={{
          x: 'max-content',
        }}
        rowHoverable={false}
        rowClassName={(record, index) => {
          return index % 2 === 0 ? '' : 'zebra-row-odd'
        }}
      />
    )
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onReply = (info: ITableData) => {
    setCurrentInfo(info)
    setreplyModalShow(true)
    FormReply.setFieldsValue({
      qualityInspector: user_info.userName ? user_info.userName + '' : '',
    })
  }
  const reloadPage = () => {
    search(params)
    getqualityTodo()
  }
  const onRun = (info: ITableData) => {
    setCurrentInfo(info)
    setrunModalShow(true)
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  const onConfirm = async (vals: any) => {
    const paramsData = {
      ...vals,
      replyQualityTime: vals.replyQualityTime && dayjs(vals.replyQualityTime).format('YYYY-MM-DD'),
      qualityOrderCode: CurrentInfo?.qualityOrderCode,
    }
    const res = await qualityReply(paramsData)
    if (res.code === 200) {
      message.success('操作成功')
      reloadPage()
      onCancel()
    }
  }
  const onConfirmRun = async (vals: any) => {
    const paramsData = {
      ...vals,
      actualQualityTime: vals.actualQualityTime && dayjs(vals.actualQualityTime).format('YYYY-MM-DD'),
      qualityOrderCode: CurrentInfo?.qualityOrderCode,
    }
    const res = await qualityExecute(paramsData)
    if (res.code === 200) {
      message.success('操作成功')
      reloadPage()
      onCancel()
    }
  }
  const onViewCon = (info: ITableData) => {
    setCurrentInfo(info)
    setconModalShow(true)
  }
  const onCancel = () => {
    setCurrentInfo({})
    setreplyModalShow(false)
    FormReply.resetFields()
    setrunModalShow(false)
    FormRun.resetFields()
    setconModalShow(false)
  }
  return (
    <PageContainer className="purchase_qc_page">
      <div className="waittodo_box">
        <div className="wait_main">
          <div className="wm_item">
            <div className="wm_item_title">待回复</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    qualityStatuses: [1],
                  })
                  search({ ...form.getFieldsValue(), createTimeStart: null, createTimeEnd: null, current: 1, size: 10 })
                  setselectedRowKeys([])
                  setselectedRowInfos([])
                }}
              >
                {CountNum.waitingReply || 0}单
              </Typography.Link>
            </div>
          </div>
          <div className="wm_item">
            <div className="wm_item_title">待执行</div>
            <div className="wm_item_num">
              <Typography.Link
                underline
                onClick={() => {
                  form.resetFields()
                  form.setFieldsValue({
                    qualityStatuses: [5],
                  })
                  search({ ...form.getFieldsValue(), createTimeStart: null, createTimeEnd: null, current: 1, size: 10 })
                  setselectedRowKeys([])
                  setselectedRowInfos([])
                }}
              >
                {CountNum.waitingExecute || 0}单
              </Typography.Link>
            </div>
          </div>
        </div>
      </div>
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['qualityOrderCode'], form)}
        searchConfig={[
          { label: 'QC订单', name: 'qualityOrderCode', type: 'Input' },
          { label: '创建时间', name: 'createTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            label: 'QC状态',
            name: 'qualityStatuses',
            type: 'Select',
            option: QC_STATUS_OPTIONS,
            config: {
              mode: 'multiple',
              maxTagCount: 'responsive',
              optionFilterProp: 'label',
            },
          },
          {
            label: '供应商',
            name: 'supplierIds',
            type: 'Select',
            option: SupplierOption,
            config: {
              mode: 'multiple',
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchSupplier,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            name: 'queryClassIdList',
            label: '款式分类',
            type: 'Cascader',
            option: classIdOptions,
            placeholder: '请选择款式分类',
            config: {
              changeOnSelect: true,
              onChange: handleClassIdChange,
              onClear: () => settinyClassIds([]),
              fieldNames: { label: 'className', value: 'classConfigId', children: 'childrenList' },
            },
          },
          { label: '预约QC时间', name: 'scheduleQualityTimeStart', type: 'RangePicker', config: { showTime: true } },
          {
            label: '采购订单',
            name: 'purchaseOrderCodes',
            placeholder: '多个单号间需要换行或使用","分隔',
            type: 'Select',
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              tokenSeparators: [',', '，', '\n', '\r', '\r\n'],
              notFoundContent: null,
            },
          },
          {
            label: 'QC人员',
            name: 'qualityInspector',
            type: 'Input',
          },
          {
            label: '供应链跟单',
            name: 'trackOrderPerson',
            type: 'Select',
            option: UserOptions,
            hidden: !isRoot,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchUser,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              fieldNames: { label: 'label', value: 'workId' },
            },
          },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
        ]}
        onFinish={(vals: any) => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          const paramsData = {
            ...vals,
            queryClassIdList: tinyClassIds.length > 0 ? tinyClassIds : null,
            createTimeStart: vals?.createTimeStart?.[0] && dayjs(vals.createTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: vals?.createTimeStart?.[1] && dayjs(vals.createTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
            scheduleQualityTimeStart:
              vals?.scheduleQualityTimeStart?.[0] &&
              dayjs(vals.scheduleQualityTimeStart[0]).format('YYYY-MM-DD HH:mm:ss'),
            scheduleQualityTimeEnd:
              vals?.scheduleQualityTimeStart?.[1] &&
              dayjs(vals.scheduleQualityTimeStart[1]).format('YYYY-MM-DD HH:mm:ss'),
          }
          search({
            ...paramsData,
          })
          setCachePage({
            ...paramsData,
            tinyClassId: vals.queryClassIdList,
            SpuOptions,
            SupplierOption,
            QcUserOptions,
            UserOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          settinyClassIds([])
          const paramsData = {
            current: 1,
            size: 10,
            createTimeStart: dayjs(defaultDateRange[0]).format('YYYY-MM-DD HH:mm:ss'),
            createTimeEnd: dayjs(defaultDateRange[1]).format('YYYY-MM-DD HH:mm:ss'),
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                permission="cancelQc"
                onClick={() => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const instance = Modal.confirm({
                    title: '提示',
                    content: '确定要取消QC吗?',
                    okText: '确认',
                    cancelText: '取消',
                    icon: <ExclamationCircleOutlined />,
                    onOk: async () => {
                      const res = await qualityBatchCancel({
                        qualityOrderCodes: selectedRowInfos?.map((item) => item.qualityOrderCode),
                      }).finally(() => {
                        instance.destroy()
                        setselectedRowKeys([])
                        setselectedRowInfos([])
                        reloadPage()
                      })
                      if (res.code === 200) {
                        message.success('操作成功')
                      }
                      if (res.code === 820000 && res.failInfo) {
                        const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                          return <div key={item}>{item}</div>
                        })
                        notification.open({
                          type: 'warning',
                          message: res.msg,
                          description: failInfo,
                        })
                      }
                    },
                  })
                }}
              >
                取消QC
              </PermissionButton>
              <Checkbox
                onChange={(event: any) => {
                  setexpand(event.target.checked)
                }}
              >
                显示明细
              </Checkbox>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportQc"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectedRowKeys.length > 0) {
                    paramsData.qualityOrderIds = selectedRowKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await qualityexport(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectedRowKeys([])
                      setselectedRowInfos([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                loading={exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({ navigate, onReply, onRun, onViewLogs, onViewCon, isRoot })}
        {...tableProps}
        expandable={{
          expandedRowKeys,
          expandedRowRender,
          onExpandedRowsChange: (keys: React.Key[]) => {
            setexpandedRowKeys(keys)
          },
        }}
        rowKey={(rows) => rows.qualityOrderId}
        tableRowGray={(record) => (record.qualityStatus && record.qualityStatus == 4 ? 'table-row-gray' : '')}
        isScrollY
        extraHeight={64}
      />
      <Drawer
        title="回复QC"
        maskClosable
        open={replyModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => FormReply.validateFields().then((values) => onConfirm(values))}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical editConfig={useFormReply()} form={FormReply} initialValues={{ replyQualityTime: dayjs() }} />
      </Drawer>
      <Drawer
        title="执行QC"
        maskClosable
        open={runModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => FormRun.validateFields().then((values) => onConfirmRun(values))}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical editConfig={useFormRun()} form={FormRun} initialValues={{ actualQualityTime: dayjs() }} />
      </Drawer>
      <Drawer title="QC结论" maskClosable open={conModalShow} onClose={onCancel}>
        <EditFormVertical editConfig={useFormCon({ CurrentInfo })} form={FormCon} />
      </Drawer>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
